package com.yxx.service.impl;

import com.yxx.mapper.ChineseWesternMedicineMapper;
import com.yxx.mapper.OrderMapper;
import com.yxx.mapper.SetMedicineMapper;
import com.yxx.mapper.UserMapper;
import com.yxx.medicinecommon.constant.StatusConstant;
import com.yxx.medicinepojo.entity.Orders;
import com.yxx.medicinepojo.vo.*;
import com.yxx.service.WorkSpaceService;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapProperties;
import org.springframework.stereotype.Service;

import java.rmi.MarshalledObject;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Year;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuxiangxun
 * @date 2024/9/18
 * @apiNote
 */
@Service
public class WorkSpaceServiceImpl implements WorkSpaceService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChineseWesternMedicineMapper chineseWesternMedicineMapper;

    @Autowired
    private SetMedicineMapper setMedicineMapper;

    /**
     * 查询订单管理数据
     * @return
     */
    @Override
    public OrderOverViewWorkSpaceVO getOrderWorkSpaceVOView() {
        // 通过 HashMap 存储各种订单状态和当前的时间（开始时间）
        Map map = new HashMap<>();
        // 将当前的时间格式转换成年月日时分作为值存储到HashMap的begin键中
        map.put("begin", LocalDateTime.now().with(LocalTime.MIN));

        //订单状态 1 待付款 2 待接单 3 已接单 4 派送中 5 已完成 6 已取消

        // 2 待接单
        Integer toBeConfirmed = Orders.TO_BE_CONFIRMED;
        map.put("status", toBeConfirmed);
        Integer toByConfirmedOrderCount = orderMapper.countMap(map);

        // 3 已接单 (待派送)
        Integer confirmed = Orders.CONFIRMED;
        map.put("status",confirmed);
        Integer confirmedOrdersCount = orderMapper.countMap(map);

        // 4 派送中 （不需要显示，前端只做了显示已接单的数据显示功能）
        Integer deliveryInProgress = Orders.DELIVERY_IN_PROGRESS;
        map.put("status",deliveryInProgress);
        Integer deliveryInProgressCount = orderMapper.countMap(map);

        // 5 已完成
        Integer completed = Orders.COMPLETED;
        map.put("status",completed);
        Integer completedCount = orderMapper.countMap(map);

        // 6 已取消
        Integer cancelled = Orders.CANCELLED;
        map.put("status",cancelled);
        Integer cancelledCount = orderMapper.countMap(map);

        //所有状态的订单
        map.put("status",null);
        Integer allOrderCount = orderMapper.countMap(map);

        //将各种订单状态封装数据到 OrderOverViewWorkSpaceVO中

        OrderOverViewWorkSpaceVO orderOverViewWorkSpaceVO =  OrderOverViewWorkSpaceVO.builder()
                .waitingOrders(toByConfirmedOrderCount)
                .deliveredOrders(confirmedOrdersCount)
                .completedOrders(completedCount)
                .cancelledOrders(cancelledCount)
                .allOrders(allOrderCount)
                .build();

        return orderOverViewWorkSpaceVO;
    }

    /**
     * 根据当天统计营业数据
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public BusinessStatisticDataVO getBusinessStatisticData(LocalDateTime beginTime, LocalDateTime endTime) {
        /**
         * 营业额：当天已完成订单的总金额
         * 有效订单：当天已完成订单的数量
         * 平均客单价：营业额/有效订单数
         * 订单完成率：有效订单数/总订单数
         */

        //创建HashMap存储当日时间的开始时间、结束时间
        Map map = new HashMap<>();
        map.put("begin",beginTime);
        map.put("end",endTime);

        //根据当日时间的开始时间和结束时间查询总订单数
        Integer totalOrderCount = orderMapper.countMap(map);

        //存储当日订单已完成的状态
        Integer completed = Orders.COMPLETED;
        map.put("status",completed);

        //根据当日时间的开始时间、结束时间、订单已完成的状态查询有效订单数
        Integer vailOrderCount = orderMapper.countMap(map);

        //总金额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null ? 0.0 : turnover;

        //平均客单价
        Double avgPrice = 0.0;

        //订单完成率
        Double orderCompletionRate = 0.0;

        if(totalOrderCount != 0 && vailOrderCount != 0){
            orderCompletionRate = vailOrderCount.doubleValue() / totalOrderCount;
            avgPrice = turnover / vailOrderCount.doubleValue();
        }

        //新增用户数
        Integer newUserCount = userMapper.countUserIdByCreateTime(map);

        //将获取到的有效订单数、总金额、平均客单价、订单完成率、新增用户数封装到 BusinessStatisticDataVO 中
        BusinessStatisticDataVO businessStatisticDataVO = BusinessStatisticDataVO.builder()
                .turnover(turnover)
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(vailOrderCount)
                .unitPrice(avgPrice)
                .newUsers(newUserCount)
                .build();
        return businessStatisticDataVO;
    }

    /**
     * 中西药总览
     * @return
     */
    @Override
    public ChineseWesternMedicineOverViewVO getChineseWesternMedicineOverView() {
        //创建一个HashMap,存储上/下架状态，通过map去动态查询到已上/下架的状态
        Map map = new HashMap();

        //获取上架的总中西药数量
        Integer enable = StatusConstant.ENABLE;
        map.put("status", enable);
        Integer enableCount = chineseWesternMedicineMapper.countByMap(map);

        //获取下架的总中西药数量
        Integer disable = StatusConstant.DISABLE;
        map.put("status",disable);
        Integer disableCount = chineseWesternMedicineMapper.countByMap(map);


        //将获取到的已上架和已下架的总中西药数量封装到 ChineseWesternMedicineOverViewVO 中
        ChineseWesternMedicineOverViewVO chineseWesternMedicineOverViewVO = ChineseWesternMedicineOverViewVO.builder()
                .sold(enableCount)
                .discontinued(disableCount)
                .build();
        return chineseWesternMedicineOverViewVO;
    }

    /**
     * 组合药总览
     * @return
     */
    @Override
    public SetmedicineOverViewVO getSetMedicineOverView() {
        //创建HashMap，存储组合药上/下架的状态，通过map动态查询组合药上/下架的数量
        Map map = new HashMap();

        //获取上架的组合药数量
        Integer enable = StatusConstant.ENABLE;
        map.put("status", enable);
        Integer enableCount = setMedicineMapper.countByMap(map);

        //获取下架的组合药数量
        Integer disable = StatusConstant.DISABLE;
        map.put("status",disable);
        Integer disableCount = setMedicineMapper.countByMap(map);

        SetmedicineOverViewVO setmedicineOverViewVO = SetmedicineOverViewVO.builder()
                .sold(enableCount)
                .discontinued(disableCount)
                .build();

        return setmedicineOverViewVO;
    }
}
